#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 更改根节点名字
    ui->treeWidget->setHeaderLabel("动物");
    // 新增顶层节点
    QTreeWidgetItem* item = new QTreeWidgetItem;
    item->setText(0,"猫");
    // 添加到顶层节点中
    ui->treeWidget->addTopLevelItem(item);

    QTreeWidgetItem* item1 = new QTreeWidgetItem;
    item1->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem;
    item2->setText(0,"鸟");
    ui->treeWidget->addTopLevelItem(item2);

    // 添加一些子节点
    // 默认是只有一列的，如果你想要多列，需要使用setColumnCount 设置
    QTreeWidgetItem* item_child = new QTreeWidgetItem;
    item_child->setText(0,"小猫");
    item->addChild(item_child);

    QTreeWidgetItem* item_child1 = new QTreeWidgetItem;
    item_child1->setText(0,"花猫");
    item->addChild(item_child1);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_add_top_clicked()
{
    QString text = ui->lineEdit->text();
    if(text.isEmpty())
        return;
    QTreeWidgetItem* item = new QTreeWidgetItem;
    item->setText(0,text);
     ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_add_child_clicked()
{
    QString text = ui->lineEdit->text();
    if(text.isEmpty())
        return;
    QTreeWidgetItem* item = new QTreeWidgetItem;
    item->setText(0,text);
    QTreeWidgetItem* cur = ui->treeWidget->currentItem();
    cur->addChild(item);
    // 展开父节点
    cur->setExpanded(true);

}

void Widget::on_pushButton_del_clicked()
{
    QTreeWidgetItem* cur = ui->treeWidget->currentItem();
    if(cur == nullptr)
        return;
    QTreeWidgetItem* parent = cur->parent();
    // 顶层节点
    if(parent == nullptr)
    {
        //查询指定节点是顶层节点中的下标
        int index = ui->treeWidget->indexOfTopLevelItem(cur);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        // Qt内部做了父子节点的连接，我们只要删除即可
        parent->removeChild(cur);
    }
}
